package org.example.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExample {

    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private int sharedResource = 0;

    public void readData() {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ": Reading data: " + sharedResource);
        } finally {
            lock.readLock().unlock();
        }
    }

    public void writeData(int newValue) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ": Writing data: " + newValue);
            sharedResource = newValue;
        } finally {
            lock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockExample example = new ReadWriteLockExample();

        Thread reader1 = new Thread(example::readData, "Reader1");
        Thread reader2 = new Thread(example::readData, "Reader2");
        Thread writer = new Thread(() -> example.writeData(10), "Writer");

        reader1.start();
        reader2.start();
        writer.start();
    }
}